package com.duoec.dw.lineage.service.analyser.expr;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLCaseExpr;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author xuwenzhen
 */
@Service
public class CaseExprExprAnalyser extends BaseExprAnalyser<SQLCaseExpr> {
    /**
     * 获取匹配类型
     *
     * @return 类型
     */
    @Override
    public Class<SQLCaseExpr> getSqlExprType() {
        return SQLCaseExpr.class;
    }

    /**
     * 分析表达式语句
     *
     * @param expr         表达式语句
     * @param fromLineages 当前语句from解析出来的血缘关系
     * @return 此表达式抽取出来的依赖
     */
    @Override
    public LinkedHashSet<TableFieldDependencyDto> analyse(SQLCaseExpr expr, MultiTableLineageDto fromLineages) {
        LinkedHashSet<TableFieldDependencyDto> dependencies = new LinkedHashSet<>();
        SQLExpr valueExpr = expr.getValueExpr();
        LinkedHashSet<TableFieldDependencyDto> dependencies1 = hiveAnalyser.analyseExpr(fromLineages, valueExpr);
        AnalyserUtils.mergeToDependencies(dependencies, dependencies1);

        List<SQLCaseExpr.Item> items = expr.getItems();
        if (!CollectionUtils.isEmpty(items)) {
            items.forEach(item -> {
                LinkedHashSet<TableFieldDependencyDto> dependencies2 = hiveAnalyser.analyseExpr(fromLineages, item.getConditionExpr());
                AnalyserUtils.mergeToDependencies(dependencies, dependencies2);
                LinkedHashSet<TableFieldDependencyDto> dependencies3 = hiveAnalyser.analyseExpr(fromLineages, item.getValueExpr());
                AnalyserUtils.mergeToDependencies(dependencies, dependencies3);
            });
        }
        LinkedHashSet<TableFieldDependencyDto> dependencies4 = hiveAnalyser.analyseExpr(fromLineages, expr.getElseExpr());
        AnalyserUtils.mergeToDependencies(dependencies, dependencies4);
        return dependencies;
    }
}
